package com.salesmanager.core.business.app.service;

import com.salesmanager.core.business.app.dao.AppChannelDao;
import com.salesmanager.core.business.app.model.AndroidChannel;
import com.salesmanager.core.business.generic.exception.ServiceException;
import com.salesmanager.core.business.generic.service.SalesManagerEntityServiceImpl;
import com.salesmanager.core.business.statistics.model.AppChannelCriteria;
import com.salesmanager.core.modules.cms.common.CmsFileManager;
import com.salesmanager.core.modules.cms.common.CmsFileManagerFacade;
import com.salesmanager.web.model.paging.PaginationDataList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Liutong on 2016/1/13.
 */
@Service("appChannelService")
public class AppChannelServiceImpl extends SalesManagerEntityServiceImpl<Long, AndroidChannel> implements AppChannelService   {


    @Autowired
    private CmsFileManager cmsFileManager;


    private CmsFileManagerFacade facade = null;

    private AppChannelDao appChannelDao;

    @Autowired
    public AppChannelServiceImpl(AppChannelDao appChannelDao) {
        super(appChannelDao);
        this.appChannelDao=appChannelDao;
    }

    private CmsFileManagerFacade getCmsFileManagerFacade(){
        if (facade == null) facade = new CmsFileManagerFacade(cmsFileManager);
        return facade;
    }

    @Override
    public PaginationDataList<AndroidChannel> getAppChannelList(AppChannelCriteria criteria) {
        return appChannelDao.getAppChannelList(criteria);
    }

    @Override
    public AndroidChannel getByChannelCode(String channelCode) throws ServiceException {
        return appChannelDao.getByChannelCode(channelCode);
    }

    @Override
    public void saveOrUpdate(AndroidChannel androidChannel) throws ServiceException {
        String oldFileName = null;
        if (androidChannel.getId()!=null){
            AndroidChannel dbChannel = super.getById(androidChannel.getId());
            oldFileName = dbChannel.getFileName();
            super.update(androidChannel);
        }else {
            super.create(androidChannel);
        }

        if (androidChannel.getApkFileInputStream()!=null){
            this.getCmsFileManagerFacade().uploadApkFile(androidChannel.getChannelCode(),androidChannel.getFileName(),androidChannel.getApkFileInputStream());

            //文件名相同会把新上传的文件删除
            if (oldFileName!=null && !oldFileName.equals(androidChannel.getFileName())){
                this.getCmsFileManagerFacade().removeApkFile(androidChannel.getChannelCode(),oldFileName);
            }
        }


    }

    @Override
    public void deleteById(Long channelId) {
        this.appChannelDao.deleteById(channelId);
    }

    @Override
    public List<AndroidChannel> getChannelCodes() {
        return appChannelDao.getChannelCodes();
    }

}
